package com.seagox.chat.config;

import com.corundumstudio.socketio.Configuration;
import com.corundumstudio.socketio.SocketConfig;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.listener.ExceptionListener;

import io.netty.channel.ChannelHandlerContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.List;

import javax.annotation.Resource;

@Component
public class MessagePushConfig implements InitializingBean {
	
	private static final Logger logger = LoggerFactory.getLogger(MessagePushConfig.class);
	
    @Resource
    private EventListenner eventListenner;
    
    @Value("${socketio.port}")
    private int port;

    @Autowired
    private SocketIOServer socketIOServer;

    @Override
    public void afterPropertiesSet() throws Exception {
        socketIOServer.start();
        logger.info("启动正常");
    }

    @Bean
    public SocketIOServer socketIOServer() {
        Configuration config = new Configuration();
        config.setPort(port);
        
        config.setExceptionListener(new ExceptionListener() {

			@Override
			public void onEventException(Exception e, List<Object> args, SocketIOClient client) {
				System.err.println("onEventException");
				
			}

			@Override
			public void onDisconnectException(Exception e, SocketIOClient client) {
				System.err.println("onDisconnectException");
				
			}

			@Override
			public void onConnectException(Exception e, SocketIOClient client) {
				System.err.println("onConnectException");
				
			}

			@Override
			public boolean exceptionCaught(ChannelHandlerContext ctx, Throwable e) throws Exception {
				System.err.println("exceptionCaught");
				ctx.close();
				return true;
			}
            
        });

        SocketConfig socketConfig = new SocketConfig();
        socketConfig.setReuseAddress(true);
        socketConfig.setTcpNoDelay(true);
        socketConfig.setSoLinger(0);
        config.setSocketConfig(socketConfig);
        SocketIOServer server = new SocketIOServer(config);
        server.addListeners(eventListenner);
        return server;
    }
}
